﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace ZHDJ.WebPage
{
    public class NPOIBusiness
    {
        /// <summary>
        /// Excel导入DataTable
        /// </summary>
        /// <param name="xlsPath">Excel路径</param>
        /// <param name="sheetName">Sheet名称</param>
        /// <param name="isFirstRowColumn">第一行是否为DataTable列名,是列名加粗</param>
        /// <returns>DataTable</returns>
        public static DataTable Import(string xlsPath, string sheetName, bool isFirstRowColumn = true)
        {
            return ConvertToDataTable(sheetName, InitializeWorkbook(xlsPath), isFirstRowColumn);
        }

        /// <summary>
        /// DataTable导出Excel为内存流
        /// </summary>
        /// <param name="sheetName">sheetName</param>
        /// <param name="dt">DataTable</param>
        /// <param name="isColumnWritten">第一行是否为Excel列名,是列名加粗</param>
        /// <returns></returns>
        public static MemoryStream Export(string sheetName, DataTable dt, bool isColumnWritten = true)
        {
            return DataTableToExcel(dt, sheetName, new Dictionary<int, int>(), isColumnWritten);
        }

        /// <summary>
        /// DataTable导出Excel为内存流
        /// </summary>
        /// <param name="sheetName">sheetName</param>
        /// <param name="dt">DataTable</param>
        /// <param name="columnWidth">列号，列宽</param>
        /// <param name="isColumnWritten">第一行是否为Excel列名,是列名加粗</param>
        /// <returns></returns>
        public static MemoryStream Export(string sheetName, DataTable dt, Dictionary<int, int> columnWidth, bool isColumnWritten = true)
        {
            return DataTableToExcel(dt, sheetName, columnWidth, isColumnWritten);
        }

        /// <summary>
        /// DataTable导出Excel为内存流
        /// </summary>
        /// <param name="sheetName">工作簿名称</param>
        /// <param name="dt">数据源</param>
        /// <param name="cellRange">合并单元格起始索引</param>
        /// <param name="isColumnWritten">第一行是否为Excel列名,是列名加粗</param>
        /// <returns></returns>
        public static MemoryStream Export(string sheetName, DataTable dt, List<CellRange> cellRange, bool isColumnWritten = true)
        {
            return DataTableToExcel(dt, sheetName, new Dictionary<int, int>(), cellRange, isColumnWritten);
        }

        /// <summary>
        /// DataTable导出Excel并保存，保存格式为97-2003
        /// </summary>
        /// <param name="savePath">保存路径</param>
        /// <param name="sheetName">sheetName</param>
        /// <param name="dt">DataTable</param>
        /// <param name="isColumnWritten">第一行是否为Excel列名,是列名加粗</param>
        public static bool ExportToSave(string savePath, string sheetName, DataTable dt, bool isColumnWritten = true)
        {
            MemoryStream memoryStream = DataTableToExcel(dt, sheetName, new Dictionary<int, int>(), isColumnWritten);
            FileStream fileStream = new FileStream(savePath, FileMode.OpenOrCreate);
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);
            binaryWriter.Write(memoryStream.ToArray());
            fileStream.Close();
            binaryWriter.Close();
            return File.Exists(savePath);
        }

        /// <summary>
        ///  DataTable导出Excel并保存，保存格式为97-2003
        /// </summary>
        /// <param name="savePath">保存路径</param>
        /// <param name="memoryStream">内存流</param>
        public bool ExportToSave(string savePath, MemoryStream memoryStream)
        {
            FileStream fileStream = new FileStream(savePath, FileMode.OpenOrCreate);
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);
            binaryWriter.Write(memoryStream.ToArray());
            fileStream.Close();
            binaryWriter.Close();
            return File.Exists(savePath);
        }

        private static MemoryStream DataTableToExcel(DataTable data, string sheetName, Dictionary<int, int> columnWidth, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;

            HSSFWorkbook iWorkbook = new HSSFWorkbook();
            ISheet sheet = iWorkbook.CreateSheet(sheetName);
            if (columnWidth != null && columnWidth.Count > 0)
            {
                foreach (int key in columnWidth.Keys)
                {
                    sheet.SetColumnWidth(key, columnWidth[key]);
                }
            }
            if (isColumnWritten == true) //写入DataTable的列名
            {
                IRow row = sheet.CreateRow(0);
                IFont columnHeadFont = iWorkbook.CreateFont();
                columnHeadFont.FontName = "宋体";
                columnHeadFont.Boldweight = 700;
                ICellStyle columnHeadStyle = iWorkbook.CreateCellStyle();
                columnHeadStyle.SetFont(columnHeadFont);
                for (j = 0; j < data.Columns.Count; ++j)
                {
                    ICell cell = row.CreateCell(j);
                    cell.CellStyle = columnHeadStyle;
                    cell.SetCellValue(data.Columns[j].ColumnName);
                }
                count = 1;
            }
            else
            {
                count = 0;
            }

            for (i = 0; i < data.Rows.Count; ++i)
            {
                IRow row = sheet.CreateRow(count);
                for (j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                }
                ++count;
            }
            MemoryStream file = new MemoryStream();
            iWorkbook.Write(file);
            return file;
        }

        private static MemoryStream DataTableToExcel(DataTable data, string sheetName, Dictionary<int, int> columnWidth, List<CellRange> cellRange, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;

            HSSFWorkbook iWorkbook = new HSSFWorkbook();
            ISheet sheet = iWorkbook.CreateSheet(sheetName);
            ICellStyle contentStyle = iWorkbook.CreateCellStyle();
            contentStyle.VerticalAlignment = VerticalAlignment.Center;

            if (columnWidth != null && columnWidth.Count > 0)
            {
                foreach (int key in columnWidth.Keys)
                {
                    sheet.SetColumnWidth(key, columnWidth[key]);
                }
            }
            if (isColumnWritten == true) //写入DataTable的列名
            {
                IRow row = sheet.CreateRow(0);
                IFont columnHeadFont = iWorkbook.CreateFont();
                columnHeadFont.FontName = "宋体";
                columnHeadFont.Boldweight = 700;
                ICellStyle columnHeadStyle = iWorkbook.CreateCellStyle();
                columnHeadStyle.SetFont(columnHeadFont);

                for (j = 0; j < data.Columns.Count; ++j)
                {
                    ICell cell = row.CreateCell(j);
                    cell.CellStyle = columnHeadStyle;
                    cell.SetCellValue(data.Columns[j].ColumnName);
                }
                count = 1;
            }
            else
            {
                count = 0;
            }

            if (cellRange != null && cellRange.Count > 0)
            {
                foreach (CellRange range in cellRange)
                {
                    sheet.AddMergedRegion(new CellRangeAddress(range.FirstRow, range.LastRow, range.FirstCol, range.LastCol));
                }
            }

            for (i = 0; i < data.Rows.Count; ++i)
            {
                IRow row = sheet.CreateRow(count);
                for (j = 0; j < data.Columns.Count; ++j)
                {
                    row.CreateCell(j).CellStyle = contentStyle;
                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                }
                ++count;
            }

            MemoryStream file = new MemoryStream();
            iWorkbook.Write(file);
            return file;
        }

        private static IWorkbook InitializeWorkbook(string path)
        {
            IWorkbook iWorkbook;
            using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                if (path.IndexOf(".xlsx") > 0) // 2007版本
                    iWorkbook = new XSSFWorkbook();
                else if (path.IndexOf(".xls") > 0) // 2003版本
                    iWorkbook = new HSSFWorkbook();
                iWorkbook = new XSSFWorkbook(file);
                return iWorkbook;
            }
        }
        private static DataTable ConvertToDataTable(string sheetName, IWorkbook iWorkbook, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable dt = new DataTable();
            int startRow = 0;
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = iWorkbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = iWorkbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = iWorkbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(0);
                int cellCount = 0;
                if (firstRow != null)
                    cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
                if (isFirstRowColumn)
                {
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                dt.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;
                }
                else
                {
                    startRow = sheet.FirstRowNum;
                }
                //最后一列的标号
                int rowCount = sheet.LastRowNum;
                for (int i = startRow; i <= rowCount; ++i)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null) continue; //没有数据的行默认是null　　　　　　　

                    DataRow dataRow = dt.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                    {
                        if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                            dataRow[j] = row.GetCell(j).ToString();
                    }
                    dt.Rows.Add(dataRow);
                }
            }
            return dt;
        }

        public class CellRange
        {
            /// <summary>
            /// 起始行（以0开始）
            /// </summary>
            public int FirstRow { get; set; }

            /// <summary>
            /// 结束行
            /// </summary>
            public int LastRow { get; set; }

            /// <summary>
            /// 起始列（以0开始）
            /// </summary>
            public int FirstCol { get; set; }

            /// <summary>
            /// 结束列
            /// </summary>
            public int LastCol { get; set; }
        }
    }
}
